#include "chat_message.h"

#include <boost/asio.hpp>

#include <deque>
#include <iostream>
#include <list>
#include <set>
#include <utility>

#include <cstdlib>

using boost::asio::ip::tcp;
using chat_message_queue = std::deque<chat_message>; //消息队列

class chat_participant {
public:
	virtual ~chat_participant() {}
	virtual void deliver(const chat_message &msg) = 0; //纯虚函数
};
using chat_participant_ptr = std::shared_ptr<chat_participant>;
/*
 * 聊天室
 * 1.join 加入 2.leave 离开 3.deliver 消息保持<100条
 */
class chat_room {
public:
	void join(chat_participant_ptr participant){
		participants_.insert(participant); //增加一个人
		for(const auto& msg : recent_msgs_){
			//auto默认按值拷贝 把聊天历史发给新用户
			participant->deliver(msg); 
			//是一个chat_participant基类指针，会调用继承类的函数
		}
		if(recent_msgs_.empty()) {
		}
	}
	void leave(chat_participant_ptr participant){
		participants_.erase(participant);
	}
	void deliver(const chat_message &msg){
		recent_msgs_.push_back(msg);
		while(recent_msgs_.size() > max_recent_msgs)
			recent_msgs_.pop_front();
		for(auto& participant : participants_){
			participant->deliver(msg);
		}
	}
private:
	std::set<chat_participant_ptr> participants_;//聊天人员队列
	enum { max_recent_msgs = 100 };
	chat_message_queue recent_msgs_;//消息队列
};
/*
 * 客户端连接成功
 * 1.start 连接 2.消息派发  3.消息读取
 */
class chat_session: public chat_participant,
										public std::enable_shared_from_this<chat_session> {
public:
	chat_session(tcp::socket socket, chat_room &room)
		: socket_(std::move(socket)), room_(room){}
	
	void start() {
		room_.join(shared_from_this());
		do_read_header();
	}

	void deliver(const chat_message &msg) {
		bool write_in_progress = !write_msgs_.empty();
		//有-true 空-false
		//first = false 刚开始为空,第一次必空
		write_msgs_.push_back(msg);
		//防止调用两次do_write();
		if(!write_in_progress) {
			//非空，first
			do_write();
		}	
	}
private:
	void do_read_header() {
		auto self(shared_from_this());//保证自己不被析构掉
		boost::asio::async_read(
				socket_, boost::asio::buffer(read_msg_.data(), chat_message::header_length),
				[this, self](boost::system::error_code ec, std::size_t /*length*/) {
					if(!ec && read_msg_.decode_header()) {
						//无网络错误，长度正常，都包体
						do_read_body();
					} else {
						room_.leave(shared_from_this());
						//leave的set把这个指针干掉，计数为0，析构
					}
				});
	}
	void do_read_body() {
		auto self(shared_from_this());
		boost::asio::async_read(
				socket_, boost::asio::buffer(read_msg_.body(), read_msg_.body_length()),
				[this, self](boost::system::error_code ec, std::size_t /*length*/) {
					if(!ec) {
						room_.deliver(read_msg_);
						do_read_header();
					}	else {
						room_.leave(shared_from_this());
					}
				});
	}
	void do_write() {
		auto self(shared_from_this());
		boost::asio::async_write(
				socket_, boost::asio::buffer(write_msgs_.front().data(),
																	   write_msgs_.front().length()),
				[this, self](boost::system::error_code ec, std::size_t /*length*/) {
					if(!ec){
						write_msgs_.pop_front();
						if(!write_msgs_.empty()) {
							do_write();//没写完继续写
						}
					} else {
						room_.leave(shared_from_this());
					}
				});
	}

	tcp::socket socket_;
	chat_room &room_; //chat_session生命周期<chat_room
	chat_message read_msg_;
	chat_message_queue write_msgs_;
};

class chat_server {
public:
	chat_server(boost::asio::io_service &io_service,
							const tcp::endpoint &endpoint) 
		: acceptor_(io_service, endpoint), socket_(io_service){
		do_accept();
	}
private:
	void do_accept() {
		acceptor_.async_accept(socket_, [this](boost::system::error_code ec) {
				if(!ec) {
					auto session = 
							std::make_shared<chat_session>(std::move(socket_), room_);
					session->start();
				}
				do_accept();//一般错误是客户端，服务端不能停
			});
	}
	
	tcp::acceptor acceptor_;
	tcp::socket socket_;//给chat_session客户端使用
	chat_room room_;//每一个chat_server就是一个chat_room
};

int main(int argc, char *argv[]) {
	try{
		if(argc < 2){
			std::cout << "Usage: chat_server <port> [<port> ...]\n";
			return 1;
		}

		boost::asio::io_service io_service;
		
		std::list<chat_server> servers;
		for(int i = 1; i < argc; ++i) {
			tcp::endpoint endpoint(tcp::v4(), std::atoi(argv[i]));
			servers.emplace_back(io_service, endpoint);
		}
		
		io_service.run();
	} catch (std::exception &e) {
		std::cout << "Exception: " << e.what() << "\n";
	}
	return 0;
}
